package com.gem.growingtree.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.gem.growingtree.activity.R;

public class HttpXUtils {
	private static final String X_URL = "http://";

	// 判断网络是否连通
	public static boolean isNetworkConnected(Activity activity) {// (ConnectivityManager)
		// getSystemService(CONNECTIVITY_SERVICE)
		ConnectivityManager manager = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo info = manager.getActiveNetworkInfo();
		return info != null && info.isConnected();
	}

	// 测试连接
	public void fetchTemp(final String testUrl) {
		new Thread() {
			@Override
			public void run() {
				try {
					URL url = new URL(testUrl);
					// 打开连接
					HttpURLConnection connection = (HttpURLConnection) url
							.openConnection();
					connection.setRequestMethod("POST");
					connection.setReadTimeout(2000);
					connection.setDoInput(true);
					connection.connect();
					if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
						String result = new String(
								StreamTool.readInputStream(connection
										.getInputStream()), "utf-8");
//						updateUI(result);
					} else {
						throw new RuntimeException("访问有错误"
								+ StreamTool.readInputStream((connection
										.getErrorStream())));
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

//			private void updateUI(final String result) {
//				runOnUiThread(new Runnable() {
//
//					@Override
//					public void run() {
//						((TextView) findViewById(R.id.weatherInfo))
//								.setText(getTempInfo(result));
//					}
//				});
//			}
		}.start();
	}

	// public void fetchData(View view) {
	// if (isNetworkConnected()) {
	// fetchTemp(X_URL);
	// } else {
	// Toast.makeText(this, "网络不可用", Toast.LENGTH_SHORT).show();
	// }
	// }
}
